# -*- coding: utf-8 -*-
import json

from datetime import datetime
from chng.items import MetaBrand
from zc_core.model.items import *
from zc_core.util.sku_id_parser import convert_id2code
from zc_core.util.encrypt_util import build_sha1_order_id, md5, short_uuid
from zc_core.util.common import parse_time, parse_number, parse_timestamp
from zc_core.pipelines.helper.catalog_helper import CatalogHelper


def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sold_count = meta.get('soldCount')
    catalog_helper = CatalogHelper()
    # shelveStatus = 0 下架
    js = json.loads(response.text)
    if js and js.get('data', {}) and js.get('data', {}).get("shelveStatus", 1):
        rs = js.get('data', {})
        item = ItemData()
        item['batchNo'] = batch_no
        item['skuId'] = str(rs.get("productId"))
        item['spuId'] = str(rs.get("spuId"))
        item['skuName'] = rs.get("productName")
        price_info = rs.get("priceInfo", {})

        if price_info:
            item['originPrice'] = price_info.get("marketPrice")
            item['salePrice'] = price_info.get("price")
        brand = rs.get("brandName")
        if brand:
            item['brandId'] = md5(brand)
            item['brandName'] = brand
        item['catalog3Id'] = rs.get('categroyCode')
        item['supplierId'] = str(rs.get("supplierId"))
        item['supplierName'] = rs.get("supplierName")
        sp_sku_id = rs.get("productCode")
        if sp_sku_id:
            item['supplierSkuId'] = sp_sku_id
            plat_code = None
            if item['supplierId'] == '378067' or '得力' in item['supplierName']:
                plat_code = 'deli'
            item['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)
        item['unit'] = rs.get("unitName", '')
        item['minBuy'] = rs.get("minNumber", '')
        item['skuImg'] = rs.get("imageUrl")
        if rs.get("updateTime"):
            item['onSaleTime'] = parse_timestamp(rs.get("updateTime"))
        item['soldCount'] = sold_count

        extension = {}
        extension['categroyCode'] = rs.get("categroyCode", '')
        extension['categroyName'] = rs.get("categroyName", '')
        extension['categroyType'] = rs.get("categroyType", '')
        item['extension'] = json.dumps(extension)
        item['genTime'] = datetime.utcnow()
        catalog_helper.fill(item)

        return item


def parse_item_cat(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')

    rs = json.loads(response.text)
    if rs and rs.get('data', {}):
        data = rs.get('data', {})
        item = ItemDataSupply()
        item['batchNo'] = batch_no
        item['skuId'] = str(sku_id)
        item['catalog1Id'] = data.get('categoryOneCode', '')
        item['catalog1Name'] = data.get('categoryOneName', '')
        item['catalog2Id'] = data.get('categoryTwoCode', '')
        item['catalog2Name'] = data.get('categoryTwoName', '')
        item['catalog3Id'] = data.get('categoryThreeCode', '')
        item['catalog3Name'] = data.get('categoryThreeName', '')
        item['catalog1Code'] = data.get('categoryCodeCustomOne', '')
        item['catalog2Code'] = data.get('categoryCodeCustomTwo', '')
        item['catalog3Code'] = data.get('categoryCodeCustomThree', '')

        return item


def fix_catalog(response):
    meta = response.meta
    catalog3_id = meta.get('catalog3Id')
    rs = json.loads(response.text)
    if rs and rs.get('data', {}):
        data = rs.get('data', {})
        catalog1Id = data.get('categoryOneCode', '')
        catalog1Name = data.get('categoryOneName', '')
        catalog2Id = data.get('categoryTwoCode', '')
        catalog2Name = data.get('categoryTwoName', '')
        catalog3Id = data.get('categoryThreeCode', '')
        catalog3Name = data.get('categoryThreeName', '')
        catalog1Code = data.get('categoryCodeCustomOne', '')
        catalog2Code = data.get('categoryCodeCustomTwo', '')
        catalog3Code = data.get('categoryCodeCustomThree', '')
        cat_list = []
        entity1 = Catalog()
        entity1['catalogId'] = catalog1Id
        entity1['catalogName'] = catalog1Name
        entity1['catalogCode'] = catalog1Code
        entity1['parentId'] = ""
        entity1['level'] = 1
        entity1['leafFlag'] = 0
        entity2 = Catalog()
        entity2['catalogId'] = catalog2Id
        entity2['catalogName'] = catalog2Name
        entity2['catalogCode'] = catalog2Code
        entity2['parentId'] = catalog1Id
        entity2['level'] = 2
        entity2['leafFlag'] = 0
        entity3 = Catalog()
        entity3['catalogId'] = catalog3Id
        entity3['catalogName'] = catalog3Name
        entity3['catalogCode'] = catalog3Code
        entity3['parentId'] = catalog2Id
        entity3['level'] = 3
        entity3['leafFlag'] = 1
        cat_list.append(entity1)
        cat_list.append(entity2)
        cat_list.append(entity3)
        return cat_list


def parse_catalog(response):
    cat_list = list()
    cat_json = json.loads(response.text)
    cat1_list_js = cat_json.get('data', [])
    for cat1_js in cat1_list_js:
        cat1 = build_catalog(cat1_js, '', 1)
        cat1_id = cat1.get('catalogId')
        cat_list.append(cat1)
        cat2_list_js = cat1_js.get('childNodeList', [])
        for cat2_js in cat2_list_js:
            cat2 = build_catalog(cat2_js, cat1_id, 2)
            cat2_id = cat2.get('catalogId')
            cat_list.append(cat2)
            cat3_list_js = cat2_js.get('childNodeList', [])
            for cat3_js in cat3_list_js:
                cat3 = build_catalog(cat3_js, cat2_id, 3)
                cat_list.append(cat3)

    return cat_list


def build_catalog(cat, pid, level):
    entity = Catalog()
    entity['catalogId'] = str(cat.get('nodeCode'))
    entity['catalogCode'] = str(cat.get('nodeid'))
    entity['catalogName'] = cat.get('nodeName')
    entity['parentId'] = str(pid)
    entity['level'] = level
    if entity['level'] == 3:
        entity['leafFlag'] = 1
    else:
        entity['leafFlag'] = 0
    entity['linkable'] = 1

    return entity


def parse_meta_brand(response):
    meta_info = {}
    rs = json.loads(response.text)
    groups = rs.get("data", {})
    if groups:
        groups = groups.get('searchGroup', {}).get('searchGroup', [])
    else:
        groups = []
    for group in groups:
        group_code = group.get('groupCode')
        meta_list = list()
        meta_info[group_code] = meta_list
        nodes = group.get('nodes', [])
        for node in nodes:
            br = node.get('name')
            num = node.get('num')
            type = 'cn'
            cn = br
            en = br
            if '（' in br and '）' in br:
                arr = br.split('（')
                cn = arr[0].strip()
                en = arr[1].replace('）', '').strip()
                type = 'cn_en'
            meta = MetaBrand()
            meta['_id'] = node.get('code')
            meta['main_brand'] = br
            meta['cn'] = cn
            meta['en'] = en
            meta['plat'] = 'chng'
            meta['type'] = type
            meta['num'] = num
            meta_list.append(meta)

    return meta_info


def parse_query_info(response):
    rs = json.loads(response.text)
    data = rs.get("data", {})
    total_pages = data.get('result', {}).get('totalPage', 0)

    group_info = {}
    for item in data.get('searchGroup', {}).get('searchGroup', []):
        group_code = item.get('groupCode')
        group_nodes = item.get('nodes')
        group_info[group_code] = group_nodes

    return total_pages, group_info


def parse_sku_list(response):
    cat_helper = CatalogHelper()
    meta = response.meta
    # cat3_id = meta.get("cat_id")
    rs = json.loads(response.text)
    result = rs.get("data", {}).get('result', {})

    sku_list = list()
    for item_sku in result.get('root', []):
        sku = Sku()
        sku['skuId'] = str(item_sku.get('productId'))
        sku['skuName'] = item_sku.get('productName')
        sku['salePrice'] = parse_number(item_sku.get('priceStr'))
        brand_code = str(item_sku.get('brandCode'))
        sku['brandId'] = md5(brand_code)
        sku['brandName'] = item_sku.get('brandName')
        sku['catalog3Id'] = item_sku.get('categoryCode').split(':')[-1]
        sku['catalog3Name'] = item_sku.get('categoryCode').split(':')[-2]
        cat_helper.fill(sku)
        sp_name = item_sku.get('supplierName')
        sku['supplierId'] = md5(sp_name)
        sku['supplierName'] = sp_name
        sku['unit'] = item_sku.get('unitName')
        sku['soldCount'] = item_sku.get('soldNum')
        sku['skuImg'] = item_sku.get('imageUrl', '')
        sku['srcContent'] = item_sku
        sku_list.append(sku)

    return sku_list


def parse_order(response):
    order_json = json.loads(response.text)
    meta = response.meta
    sku_id = meta.get("skuId")
    supplier_id = meta.get("supplierId")
    supplier_name = meta.get("supplierName")
    orders = list()
    batch_no = meta.get('batchNo')

    prev_order = None
    same_order_no = 1
    for order in order_json.get("list"):
        entity = OrderItem()
        entity["amount"] = order.get("subtotal")
        entity["batchNo"] = batch_no
        entity["count"] = order.get("num")

        order_detail = order.get("order")
        entity["deptId"] = md5(order_detail.get("purchaserName"))
        entity["orderDept"] = order_detail.get("purchaserName")
        entity["orderTime"] = parse_time(order_detail.get("completedAt"))
        entity["skuId"] = sku_id
        entity["supplierId"] = supplier_id
        entity["supplierName"] = supplier_name

        order_timestamp = order_detail.get("completedAt")

        if prev_order and prev_order.equals(entity):
            same_order_no = same_order_no + 1
        else:
            same_order_no = 1
        addition = {
            'sameOrderNo': same_order_no,
            'orderTimeStr': order_timestamp,
        }
        sha1_id = build_sha1_order_id(entity, addition)
        entity['id'] = sha1_id
        entity['orderId'] = sha1_id
        entity["genTime"] = datetime.utcnow()
        orders.append(entity)
        prev_order = entity
    return orders


# 解析group关系
def parse_group(response):
    meta = response.meta
    batch_no = meta.get("batchNo")
    sku_id = meta.get('skuId')
    rs = json.loads(response.text)
    spu_id = short_uuid()
    group = ItemGroup()
    if rs and isinstance(rs, list):
        ids = list()
        group['skuIdList'] = ids
        group['spuId'] = spu_id
        group['batchNo'] = batch_no
        group['skuId'] = sku_id
        for same_sku in rs:
            same_sku_id = str(same_sku.get("id"))
            ids.append(same_sku_id)

    return group
